# ZhipuAI api_key

from dotenv import load_dotenv
import os
import requests
import json

load_dotenv()  #不能用其它的文件名。

api_key = os.getenv("ZHIPUAI_API_KEY")

print(api_key)

question = input("请输入问题：") or "20字介绍北京"

url = "https://open.bigmodel.cn/api/paas/v4/chat/completions" 

headers = {

    "Content-Type": "application/json", 
    "Authorization": f"Bearer {api_key}"
    
}
data = {
    "model": "glm-4-flash",
    "messages":
        [
            {"role": "user", "content": question}
            ],
    "stream": True  
    # "stream":False  # 默认
}

response = requests.post(url, headers=headers, data=json.dumps(data))
for line in response.iter_lines():
    if line:
        delta_line = json.loads(line.decode('utf-8')[6:])
        decoded_line = delta_line['choices'][0]['delta']['content'] 
        print(decoded_line, end="")
        if decoded_line.endswith("。"):    #关键
            break
print()


